package com.xn.app.muying.fragment;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xn.app.muying.R;
import com.xn.app.muying.activity.EducationDetailsActivity;
import com.xn.app.muying.adpter.HomeKePuAdapter;
import com.xn.app.muying.bean.HomeKePuBean;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AppConstant;
import com.xn.app.muying.util.HttpUtil;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyImageLoader;
import com.xn.app.muying.util.NetworkUtil;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.view.MyListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * 女性检查项目
 * Created by Administrator on 2016/10/14.
 */
public class KePuWomanFragment extends Fragment implements MyListView.IXListViewListener {
    private Handler handler = new Handler();
    private ArrayList<HomeKePuBean> list = new ArrayList<>();
    ;
    private HomeKePuAdapter adapter;
    private HomeKePuBean bean;
    private MyListView lv;
    /**
     * 图片缓存
     */
    private ImageLoader imageLoader = null;
    private DisplayImageOptions options = null;
    //加载框
    AlertDialog dialog;
    //数据总量
    private int totalCount = 0;
    //数据获取当前页
    private int currentPage = 1;
    //每次访问数据数量
    private int number = 20;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.kepu_fragment, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        imageLoader = MyImageLoader.getImageLoader(getContext());
        // DisplayImageOptions对象是对下载好以后的图片，在显示出来的时候做的设置
        options = new DisplayImageOptions.Builder().showImageOnLoading(0) // 在下载期间显示的图片
                .showImageForEmptyUri(0) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(0) // 设置图片加载或解码过程中发生错误显示的图片
                .bitmapConfig(Bitmap.Config.RGB_565) // 防止内存溢出的，图片太多就这这个
                .cacheInMemory(true).cacheOnDisc(true).build();
        lv = (MyListView) view.findViewById(R.id.kepu_fragment_lv);
        adapter = new HomeKePuAdapter(getActivity(), handler, imageLoader, options);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Intent intent = new Intent();
                intent.putExtra("type", 1);
                intent.putExtra("id", list.get(position).getId());
                intent.putExtra("name", list.get(position).getTitle());
                intent.putExtra("title", list.get(position).getTitle());
                intent.putExtra("content", list.get(position).getContent());
                intent.putExtra("pic", list.get(position).getPictureUrl());
                intent.setClass(getActivity(), EducationDetailsActivity.class);
                getActivity().startActivity(intent);

            }
        });
        //获取列表数据
        if (NetworkUtil.isNetworkAvailable(getContext())) {
            dialog = new MyAlertDialog().ShowDialog(getActivity(), R.layout.dialog_loading);
            dialog.setCancelable(true);
            getData();
        } else {
            ToastUtil.showToast(getActivity(), R.string.no_network_hint);
        }

    }

    public void getData() {
        try {
            HttpUtil.getData(APIMethod.Home_KePu2(currentPage, number), handler, new HttpUtil.OnGetDataListener() {
                @Override
                public void onJsonData(String data) {
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        if (totalCount == 0) {
                            totalCount = jsonObject.getInt("totalCount");
                        }
                        JSONArray array = jsonObject.getJSONArray("items");
                        for (int i = 0; i < array.length(); i++) {
                            JSONObject object = array.getJSONObject(i);
                            String id = object.optString("id");
                            String name = object.optString("name");
                            String title = object.optString("title");
                            String pictureUrl = object.optString("pictureUrl");
                            String content = object.optString("shortDescription");

                            bean = new HomeKePuBean();
                            bean.setId(id);
                            bean.setName(name);
                            bean.setTitle(title);
                            bean.setPictureUrl(pictureUrl);
                            bean.setContent(content);
                            list.add(bean);

                        }
                        onLoad();
                        lv.setPullLoadEnable(true);
                        lv.setXListViewListener(KePuWomanFragment.this, totalCount, currentPage, number);
                        adapter.getData(list);
                        dialog.dismiss();
                        if (lv.getVisibility() == View.GONE) {
                            lv.setVisibility(ListView.VISIBLE);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //上拉加载
    @Override
    public void onLoadMore() {
        if (NetworkUtil.isNetworkAvailable(getActivity())) {
            if (totalCount > currentPage * number) {
                currentPage = currentPage + 1;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(AppConstant.THREAD_SLEEP);
                            getData();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            } else {
                onLoad();
            }
        } else {
            onLoad();
            ToastUtil.showToast(getActivity(), R.string.no_network_hint);
        }

    }

    @SuppressLint("SimpleDateFormat")
    private void onLoad() {
        lv.stopLoadMore();
    }
}
